package cn.cuilan.common.entity;

import cn.cuilan.common.utils.ByteUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@Data
public class HttpEntity extends ProtocolMessage {

    // 报文头长度所占字节数
    private static final int HEAD_LENGTH = 4;

    // 报文长度
    private byte[] length;

    // 全报文数据，包含报文长度
    private byte[] message;

    private String url;

    private String method;

    private Map<String, String> headers;

    private Map<String, String> formData;

    private byte[] body;

    @Override
    public void pack() {
        log.info("========================= pack =========================");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", this.url);
        jsonObject.put("method", this.method);
        jsonObject.put("headers", this.headers);
        jsonObject.put("body", this.body);
        String json = jsonObject.toJSONString();
        // 计算报文长度
        this.length = ByteUtils.intToBytes(json.length());
        byte[] jsonBytes = json.getBytes();
        byte[] messageBytes = new byte[json.length() + HEAD_LENGTH];
        // 复制长度
        System.arraycopy(length, 0, messageBytes, 0, HEAD_LENGTH);
        // 复制消息报文
        System.arraycopy(jsonBytes, 0, messageBytes, HEAD_LENGTH, jsonBytes.length);
        this.message = messageBytes;

        log.info("message length: {}", json.length());
        log.info("========================= pack end =========================");
    }

    @Override
    public void unpack() {
        log.info("========================= unpack =========================");
        String json = new String(this.message);
        HttpEntity httpEntity = JSON.parseObject(json, HttpEntity.class);
        this.url = httpEntity.url;
        this.method = httpEntity.method;
        this.headers = httpEntity.headers;
        this.body = httpEntity.body;

        log.info("message length: {}", this.message.length);
        log.info("========================= unpack end =========================");
    }

}
